var dragMaster2 = (function() {

    var dragObject
    var mouseOffset

    var dropTargets = []

    function mouseUp(e){
		e = fixEvent(e)

		for(var i=0; i<dropTargets.length; i++){
			var targ  = dropTargets[i]
			var targPos    = getPosition(targ)
			var targWidth  = parseInt(targ.offsetWidth)
			var targHeight = parseInt(targ.offsetHeight)

			if(
			(e.pageX > targPos.x)                &&
			(e.pageX < (targPos.x + targWidth))  &&
			(e.pageY > targPos.y)                &&
			(e.pageY < (targPos.y + targHeight))){
				alert("dragObject was dropped onto currentDropTarget!")
			}
		}

		dragObject = null
		removeDocumentEventHandlers()
    }

	function removeDocumentEventHandlers() {
		document.onmousemove = null
		document.onmouseup = null
		document.ondragstart = null
		document.body.onselectstart = null
	}

	function getMouseOffset(target, e) {
		var docPos	= getPosition(target)
		return {x:e.pageX - docPos.x, y:e.pageY - docPos.y}
	}


	function mouseMove(e){
		e = fixEvent(e)

		with(dragObject.style) {
			position = 'absolute'
			top = e.pageY - mouseOffset.y + 'px'
			left = e.pageX - mouseOffset.x + 'px'
		}
		return false
	}

	function mouseDown(e) {
		e = fixEvent(e)
		if (e.which!=1) return

		dragObject  = this
		mouseOffset = getMouseOffset(this, e)

		addDocumentEventHandlers()

		return false
	}

	function addDocumentEventHandlers() {
		document.onmousemove = mouseMove
		document.onmouseup = mouseUp

		// отменить перенос и выделение текста при клике на тексте
		document.ondragstart = function() { return false }
		document.body.onselectstart = function() { return false }
	}

    return {

		makeDraggable: function(element){
			element.onmousedown = mouseDown
		},

		addDropTarget: function(dropTarget){
			dropTargets.push(dropTarget)
		}
    }
}())

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}
